import { ApiResponse, SearchRes, Suggestion } from '@/types/data'
import { RootThunkAction, SearchAction } from '@/types/store'
import request from '@/utils/request'
import { removeLocalHistories, setLocalHistories } from '@/utils/storage'

export const getSuggestionList = (key: string): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{ options: Suggestion }>>(
      '/suggestion',
      {
        params: {
          q: key,
        },
      }
    )
    let list: Suggestion
    if (res.data.data.options[0] === null) {
      list = []
    } else {
      list = res.data.data.options
    }
    dispatch({
      type: 'search/getSuggestionList',
      payload: list,
    })
  }
}

export const addHistory = (key: string): RootThunkAction => {
  return (dispatch, getState) => {
    let histories = getState().search.history

    // 1. 基于 key ,判断是否重复,如果重复,需要删除处重复的
    histories = histories.filter((item) => item !== key)

    // 2.基于 key ,判断长度是否超了,删除最后一个
    if (histories.length >= 10) {
      histories.pop()
    }
    histories = [key, ...histories]

    // 3.保存 redux
    dispatch({
      type: 'search/saveHistory',
      payload: histories,
    })
    // 保存到本地
    setLocalHistories(histories)
  }
}

// 清空历史
export const clearHistory = (): RootThunkAction => {
  return (dispatch) => {
    // 1/清除redux
    dispatch({
      type: 'search/saveHistory',
      payload: [],
    })

    // 2.清除本地
    removeLocalHistories()
  }
}

// 删除某个历史
export const delHistory = (key: string): RootThunkAction => {
  return (dispatch, getState) => {
    // 1从搜索历史数组中,移除key这项 => 保留所有其他
    let histories = getState().search.history
    histories = histories.filter((item) => item !== key)
    dispatch({
      type: 'search/saveHistory',
      payload: histories,
    })

    // 2.将最新的本地
    setLocalHistories(histories)
  }
}

// 获取搜索列表
export const getSearchList = (
  page: number,
  keyword: string
): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<SearchRes>>('/search', {
      params: {
        page: page,
        per_page: 10,
        q: keyword,
      },
    })
    dispatch({
      type: 'search/getResults',
      payload: res.data.data,
    })
  }
}

// 重置resultsObj
export const clearResObj = (): SearchAction => {
  return {
    type: 'search/clearResObj',
  }
}
